let instance

let max_score = 0

export default class Score {
  constructor() {
    if (instance)
      return instance

    instance = this
  }

  lastSocre(){

    wx.getUserCloudStorage({
      keyList: ['score'],
      success: function (res) {
        console.log(res)
        let kVDataList = res["KVDataList"]
        for (let i = 0; i < kVDataList.length; i++) {
          let info = kVDataList[i]
          if (info.key === "score") {
            let wxgame_str = info.value
            let wxgame = JSON.parse(wxgame_str)
            let score_last = wxgame["wxgame"]["score"]
            if (score_last !== undefined){
              max_score = score_last
            }
          }
        }
      },
      fail: (res) => { console.log(res) }
    })
  }

  saveScore(score_in) {

    if (max_score < score_in) {

      max_score = score_in

      let gameScoreData = {
        wxgame: {
          score: score_in,
          update_time: new Date().getTime(),
        },
      }

      let userKVData = {
        key: "score",
        value: JSON.stringify(gameScoreData),
      }

      wx.setUserCloudStorage({
        'KVDataList': [userKVData],
        'success': (res) => {
          console.log(res)
        }
      })
    }
  }
}